#coding=utf-8
from playwright.sync_api import sync_playwright
import time
import subprocess
import os
import traceback
from loguru import logger
import datetime
import pandas as pd
import zipfile
import json
import requests
from decimal import *

class Walmart:
    def __init__(self, playwright):
        self.playwright = playwright
        now = datetime.datetime.now().strftime('%Y-%m-%d')
        self.server_url = 'http://192.168.3.49:8990'
        self.bill_download_path = os.path.join(os.getcwd(), '沃尔玛账单下载配置表.xlsx')
        self.bill_field_setting_path = os.path.join(os.getcwd(), '沃尔玛账单字段配置表.xlsx')
        self.storeId = '45'
        self.month_dict = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6, 'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}

    def login(self):
        for i in range(3):
            try:
                os.system('taskkill /F /IM chrome.exe')
                time.sleep(3)
                command = r"C:\Program Files\Google\Chrome\Application\chrome.exe --window-size=1600,1024 --remote-debugging-port=9001"
                print("浏览器路径：", command)
                subprocess.Popen(command)
                time.sleep(5)
                chromium = playwright.chromium.connect_over_cdp(r"http://localhost:9001")
                context = chromium.new_context(accept_downloads=True)
                self.page = context.new_page()
                # context = chromium.contexts[0]
                # self.page = context.pages[0]
                self.page.goto('https://login.account.wal-mart.com/authorize?responseType=code&state=ZXHEUXGIOK&scope=openId&nonce=O8LJJE62UW&clientType=seller&redirectUri=https://seller.walmart.com/aurora/v1/auroraScCoreService/rest/login/sso/hook&clientId=66620dfd-1f3f-479b-8b9c-e11f36c5438b')
                self.wait(self.page)
                self.page.fill('input[data-automation-id="uname"]', 'szyy@tjwanda.com')
                time.sleep(0.5)
                self.page.fill('input[data-automation-id="pwd"]', '!QAZ2wsx34')
                time.sleep(0.5)
                self.page.click('button[data-automation-id="loginBtn"]')
                time.sleep(5)
                self.page.goto('https://login.account.wal-mart.com/authorize?responseType=code&state=ZXHEUXGIOK&scope=openId&nonce=O8LJJE62UW&clientType=seller&redirectUri=https://seller.walmart.com/aurora/v1/auroraScCoreService/rest/login/sso/hook&clientId=66620dfd-1f3f-479b-8b9c-e11f36c5438b')
                # self.page.query_selector('img[alt="user-avatar"]')
                logger.info('登录沃尔玛成功')
                for i in range(20):
                    logger.info(f'等待页面加载【{i}】秒')
                    try:
                        if self.page.query_selector('a:text-is("Items")') is not None and self.page.query_selector('a:text-is("Items")').is_visible():
                            break
                    except:
                        pass
                    time.sleep(1)
                return True
            except:
                logger.info(traceback.format_exc())
        return False

    def send_to_server(self, url, data):
        headers = {'content-type': 'application/json'}
        res = requests.post(f'{self.server_url}/{url}',
                            data=json.dumps(data), headers=headers)
        logger.info(res.text)

    def wait(self, page, seconds=1):
        page.wait_for_load_state(state="domcontentloaded")
        time.sleep(seconds)

    def download_bill(self, page):
        page.click('a:has-text("Payments")')
        self.wait(page)
        page.click('#select-button')
        time.sleep(0.5)
        # 读取最近下载周期
        df = pd.read_excel(self.bill_download_path)
        field_df = pd.read_excel(self.bill_field_setting_path)
        field_df.fillna('', inplace=True)
        newest_period = df['最近下载周期'].values.tolist()[-1]
        # 获取查询周期列表
        div_list = page.query_selector_all('div.items-start:visible')
        period_list = []
        index_list = []
        for d_index, div in enumerate(div_list):
            # data-automation-id="report-option-period-0"
            data_automation_id = div.get_attribute('data-automation-id')
            if data_automation_id is not None and 'report-option-period-' in data_automation_id:
                period_list.append(div)
                index_list.append(d_index)
        data_list = []
        period = ''
        current_month = datetime.datetime.now().month
        for div_index, div in enumerate(period_list):
            data = {}
            period_text = div.text_content().strip()
            if period_text != newest_period and 'Open' not in period_text:
                logger.info(f'当前查询周期：{period_text}')
                if period == '':
                    period = period_text
                time.sleep(1)
                class_name = page.query_selector_all('div.items-start:visible')[index_list[div_index]].get_attribute("class")
                if 'cursor-pointer' in class_name:
                    page.query_selector_all('div.items-start:visible')[index_list[div_index]].click()
                    self.wait(page)
                    time.sleep(3)
                    data['period'] = period_text
                    for index, row in field_df.iterrows():
                        if str(row['字段名']) not in data.keys():
                            data[str(row['字段名'])] = Decimal(self.get_money(str(row['data-test-id']), str(row['字段名'])))
                        else:
                            data[str(row['字段名'])] = data[str(row['字段名'])] + Decimal(self.get_money(str(row['data-test-id']), str(row['字段名'])))
                    # 账单月份，通过peirod切割判断，示例：Feb 24, 2024 - Mar 9, 2024
                    # 如果结束周期的月份不是当前月份，结束周期的月份就是账单月份，
                    # 如果结束周期的月份是当前月份，则那些没下载过的周期全部归属到上个月
                    end_date = period_text.split('-')[-1].strip()
                    end_date, year_value = end_date.split(',')
                    month, day = end_date.strip().split(' ')
                    month_value = self.month_dict[month]
                    if current_month != month_value:
                        bill_month = datetime.datetime(int(year_value.strip()), month_value, 1).strftime('%Y-%m')
                    else:
                        bill_month = (datetime.datetime(int(year_value.strip()), month_value, 1) - datetime.timedelta(days=1)).strftime('%Y-%m')
                    data['billMonth'] = bill_month
                    data_list.append(data)
                    page.click('#select-button')
                    time.sleep(1)
            elif str(period_text).strip() == str(newest_period).strip():
                break
        result_list = []
        for data in data_list:
            for bill_type, bill_amount in data.items():
                if 'period' != bill_type and 'billMonth' != bill_type:
                    row = {'billMonth': data['billMonth'], 'period': data['period'], 'storeId': self.storeId, 'billType': bill_type, 'billAmount': str(bill_amount)}
                    result_list.append(row)
        # 更新查询周期
        df = df.append({'最近下载周期': period}, ignore_index=True)
        df.to_excel(self.bill_download_path, index=False)
        logger.info(result_list)
        self.send_to_server('api/v1/walmartBill/rpaImportSysWalmartBill', result_list)

    def get_money(self, data_test_id, fieldName):
        try:
            if data_test_id == '':
                return '0'
            text = self.page.query_selector(f'div.text-right:has(div[data-testid="{data_test_id}"])').text_content().strip()
            text = text.replace('$', '').replace(',', '').replace(' ', '').replace('−', '-')
            return text
        except:
            logger.info(f'获取【{fieldName}】的值失败')
            # logger.info(traceback.format_exc())
            return '0'


    def run(self):
        logger.add(os.path.join(os.getcwd(), 'logs', f'walmart_bill_{datetime.datetime.now().strftime("%Y-%m-%d")}.txt'))
        for i in range(3):
            try:
                if self.login():
                    self.download_bill(self.page)
                    break
            except:
                logger.info(traceback.format_exc())

with sync_playwright() as playwright:
    walmart = Walmart(playwright)
    walmart.run()
